//
//  sdkCall.m
//  sdkDemo
//
//  Created by qqconnect on 13-3-29.
//  Copyright (c) 2013年 qqconnect. All rights reserved.
//

#import "ShareSDKManage.h"
#import "sdkDef.h"

static ShareSDKManage *g_instance = nil;
@interface ShareSDKManage()

@end

@implementation ShareSDKManage

@synthesize oauth = _oauth;

+ (ShareSDKManage *)shareInstance{
    
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        g_instance = [[super allocWithZone:nil] init];
    });

    return g_instance;
}

+ (void)showInvalidTokenOrOpenIDMessage{
    [[NSUserDefaults standardUserDefaults] setValue:@"" forKey:@"QQ_token"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"api调用失败" message:@"可能授权已过期，请重新获取" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
}

- (void)showActionSheet{

    AWActionSheet *sheet = [[AWActionSheet alloc] initWithIconSheetDelegate:self ItemCount:[self numberOfItemsInActionSheet]];
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    [sheet showInView:window];
}

+ (void)resetSDK{
    g_instance = nil;
}

- (id)init{
//    if (self = [super init])
//    {

    
        
    //}
    return self;
}

#pragma mark - 自定义sheet 回调 -

-(int)numberOfItemsInActionSheet{
    return 8;
}

-(AWActionSheetCell *)cellForActionAtIndex:(NSInteger)index{
    AWActionSheetCell* cell = [[AWActionSheetCell alloc] init];
    
    
    cell.index = index;
    NSString *title = nil;
    NSString *imageName = @"";
    switch (index) {
        case 0:
            title = @"微信好友";
            imageName = @"sns_icon_22.png";
            break;
            
        case 1:
            title = @"微信朋友圈";
            imageName = @"sns_icon_23.png";
            break;
        case 2:
            title = @"新浪微博";
            imageName = @"sns_icon_1.png";
            break;
        case 3:
            title = @"QQ";
            imageName = @"sns_icon_24.png";
            break;
        case 4:
            title = @"腾讯微博";
            imageName = @"sns_icon_2.png";
            break;
        case 5:
            title = @"邮件";
            imageName = @"sns_icon_18.png";
            break;
        case 6:
            title = @"保存至手机相册";
            imageName = @"sns_icon_22.png";
            break;
    }
    
    [cell iconView].image = [UIImage imageNamed:imageName];
    cell.titleLabel.text = title;
    
    return cell;
}

-(void)DidTapOnItemAtIndex:(NSInteger)index{
    NSLog(@"tap on %d",index);
    
    switch (index) {
        case 0:
            // @"微信好友";
            [self WechatShare:WXSceneSession];
            break;
            
        case 1:
            //            title = @"微信朋友圈";
            [self WechatShare:WXSceneTimeline];
            break;
        case 2:
            //            title = @"新浪微博";
            [self StartSinaShare];
            break;
        case 3:
            //            title = @"QQ";
            [self qzoneOAuth];
            break;
        case 4:
            //            title = @"腾讯微博";
            [self tencentweibo];
            break;
        case 5:
            //            title = @"邮件";
            [self sendEmail];
            break;
        case 6:
            //            title = @"保存至手机相册";
            [self screenShot];
            break;
    }
}

#pragma mark - 微信分享回调 -
-(void)onResp:(BaseResp *)resp{
    
    
    NSString *labelText = nil;
    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        switch (resp.errCode) {
            case 0:
                labelText = @"分享成功";
                break;
            case -1:
                labelText = @"普通错误";
                break;
            case -2:
                labelText = @"取消分享";
                break;
            case -3:
                labelText = @"分享失败";
                break;
            case -4:
                labelText = @"认证失败";
                break;
            case -5:
                labelText = @"微信不支持";
                break;
            default:
                break;
        }
        
        DLog(@"%@",labelText);
    }
}

#pragma mark - 微信分享
- (void)WechatShare:(int)iShareType
{
    
    if (![WXApi isWXAppInstalled])
    {
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:nil message:@"没有安装微信客户端" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    //    if (![self CheckNetworkState])
    //    {
    //        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"错误" message:@"网络错误，请检查网络连接" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    //        [alert show];
    //        return;
    //    }
    
    WXMediaMessage *message = [WXMediaMessage message];
    [message setThumbImage:[UIImage imageNamed:@"app_default_244.png"]];
    
    WXImageObject *ext = [WXImageObject object];
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"app_default_244" ofType:@"png"];
    ext.imageData = [NSData dataWithContentsOfFile:filePath];
    
    //UIImage* image = [UIImage imageWithContentsOfFile:filePath];
    UIImage* image = [UIImage imageWithData:ext.imageData];
    ext.imageData = UIImagePNGRepresentation(image);
    
    //    UIImage* image = [UIImage imageNamed:@"res5thumb.png"];
    //    ext.imageData = UIImagePNGRepresentation(image);
    
    message.mediaObject = ext;
    
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = iShareType;
    
    [WXApi sendReq:req];
}

#pragma mark - 微博 -
- (void)StartSinaShare{
    [self DoSinaShare];
    return;
    NSString *sina_weibo_token = [[NSUserDefaults standardUserDefaults] valueForKey:@"sina_weibo_token"];
    if (sina_weibo_token == nil || sina_weibo_token.length == 0)
    {
        WBAuthorizeRequest *request = [WBAuthorizeRequest request];
        request.redirectURI = kSinaWeiBoRedirectURI;
        request.scope = @"all";
        [WeiboSDK sendRequest:request];
    }else{
        [self DoSinaShare];
    }
    
}

- (void)DoSinaShare{
    if (![WeiboSDK isWeiboAppInstalled])
    {
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:nil message:@"没有安装微信客户端" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    //    if (!CheckNetworkState())
    //    {
    //        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"错误" message:@"网络错误，请检查网络连接" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    //        [alert show];
    //        return;
    //    }
    
    //    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:[self messageToShare]];
    [WeiboSDK sendRequest:request];
}

- (WBMessageObject *)messageToShare{
    WBMessageObject *message = [WBMessageObject message];
    NSString *txt = @"luaijosdjlkdfsljdfksdfsjlkdsf！";
    
    message.text = txt;
    
    WBImageObject *imageo = [[WBImageObject alloc] init];
    imageo.imageData = UIImagePNGRepresentation([UIImage imageNamed:@"app_default_16.png"]);
    
    message.imageObject = imageo;
    
    return message;
}

#pragma mark - 新浪微博 -
- (void)didReceiveWeiboResponse:(WBBaseResponse *)response{
    if ([response isKindOfClass:WBSendMessageToWeiboResponse.class])
    {
        NSString *title = @"发送结果";
        NSString *message = [NSString stringWithFormat:@"响应状态: %d\n响应UserInfo数据: %@\n原请求UserInfo数据: %@",(int)response.statusCode, response.userInfo, response.requestUserInfo];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }else if ([response isKindOfClass:WBAuthorizeResponse.class])
    {
        NSString *title = @"认证结果";
        NSString *message = [NSString stringWithFormat:@"响应状态: %d\nresponse.userId: %@\nresponse.accessToken: %@\n响应UserInfo数据: %@\n原请求UserInfo数据: %@",
                             response.statusCode, [(WBAuthorizeResponse *)response userID], [(WBAuthorizeResponse *)response accessToken], response.userInfo, response.requestUserInfo];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        
        NSString * wbtoken = [(WBAuthorizeResponse *)response accessToken];
        if(wbtoken.length > 0)
            [[NSUserDefaults standardUserDefaults] setValue:wbtoken forKey:@"sina_weibo_token"];
        [alert show];
    }
}

- (void)didReceiveWeiboRequest:(WBBaseRequest *)request{
    DLog(@"收到来自微博的请求");
}

#pragma mark - QQ -

-(void)qzoneImage{
    
    NSString *imgPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"app_default_244.png"];
    NSData *imgData = [NSData dataWithContentsOfFile:imgPath];
    QQApiImageObject *imgObj = [QQApiImageObject objectWithData:imgData
                                               previewImageData:imgData
                                                          title:@"tttttt"
                                                    description:@"tttttt空间分享"];
    SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:imgObj];
    //将内容分享到qq
    QQApiSendResultCode sent = [QQApiInterface sendReq:req];
    DLog(@"%d",sent);
}

- (void)qzoneOAuth{
    
    if(![QQApi isQQInstalled]){
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"操作失败" message:@"未安装"
							  
													   delegate:self cancelButtonTitle:@"我知道啦" otherButtonTitles: nil];
		[alert show];
        return;
    }
    
    if(!_oauth){
        _oauth = [[TencentOAuth alloc] initWithAppId:kQQKey andDelegate:self];
    }
    NSString *QQ_token = [[NSUserDefaults standardUserDefaults] valueForKey:@"QQ_token"];
    if(QQ_token && QQ_token.length){
        _oauth.accessToken = QQ_token;
        [self qzoneImage];
    }else{
        [_oauth authorize:[NSArray arrayWithObjects:@"all", nil] inSafari:NO];
    }
}

-(void)tencentweibo{
    
    if(!_oauth){
        _oauth = [[TencentOAuth alloc] initWithAppId:kQQKey andDelegate:self];
    }
    
    
    NSString *QQ_token = [[NSUserDefaults standardUserDefaults] valueForKey:@"QQ_token"];
    if(QQ_token && QQ_token.length){
        _oauth.accessToken = QQ_token;
        
        WeiBo_add_pic_t_POST *request = [[WeiBo_add_pic_t_POST alloc] init];
        request.param_pic = [UIImage imageNamed:@"app_default_16.png"];
        request.param_content = @"xxxxxxxxxxxxxx";
        request.param_compatibleflag = @"0x2|0x4|0x8|0x20";
        request.param_latitude = @"39.909407";
        request.param_longitude = @"116.397521";
        
        if(NO == [_oauth sendAPIRequest:request callback:self])
        {
            [ShareSDKManage showInvalidTokenOrOpenIDMessage];
        }
        else
        {
            DLog(@"微博分享成功");
        }
        
    }else{
        [_oauth authorize:[NSArray arrayWithObjects:@"all", nil] inSafari:NO];
    }
}

#pragma mark - 邮箱 -
- (void)sendEmail{
    
    double delayInSeconds = 1.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
        mc.mailComposeDelegate = self;
        [mc setSubject:@"标题"];
        [mc setToRecipients:[NSArray arrayWithObject:@"1142130116@qq.com"]];
        
        
        NSData *data = UIImagePNGRepresentation([UIImage imageNamed:@"app_default_16.png"]);
        [mc addAttachmentData:data mimeType:@"image/png" fileName:@"blood_orange"];
        
        UIWindow *window = [[UIApplication sharedApplication] keyWindow];
        
        UIViewController *v = window.rootViewController;
        [v presentViewController:mc animated:YES completion:^{
            ;
        }];
    });
    
    
}

- (void)mailComposeController:(MFMailComposeViewController*)controller
          didFinishWithResult:(MFMailComposeResult)result
                        error:(NSError*)error {
    switch (result)
    {
        case MFMailComposeResultCancelled:
            DLog(@"Mail send canceled...");
            break;
        case MFMailComposeResultSaved:
            DLog(@"Mail saved...");
            break;
        case MFMailComposeResultSent:
            DLog(@"Mail sent...");
            break;
        case MFMailComposeResultFailed:
            DLog(@"Mail send errored: %@...", [error localizedDescription]);
            break;
        default:
            break;
    }
    [controller dismissViewControllerAnimated:YES completion:NULL];
}
#pragma mark - 保存到本地 -
- (void)screenShot{
       
    
    if(self.shareImage)
        UIImageWriteToSavedPhotosAlbum(self.shareImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    else
        DLog(@"失败");
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    // Was there an error?
    if (error != NULL)
    {
        // Show error message...
        DLog(@"");
    }
    else  // No errors
    {
        // Show message image successfully saved
        DLog(@"");
    }
}


#pragma mark - QQ回调 -
- (void)tencentDidLogin{
    DLog(@"");
    [[NSUserDefaults standardUserDefaults] setValue:_oauth.accessToken forKey:@"QQ_token"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [[NSNotificationCenter defaultCenter] postNotificationName:kLoginSuccessed object:self];
}

- (void)tencentDidNotLogin:(BOOL)cancelled{DLog(@"");
    [[NSNotificationCenter defaultCenter] postNotificationName:kLoginFailed object:self];
}

- (void)tencentDidNotNetWork{DLog(@"");
    [[NSNotificationCenter defaultCenter] postNotificationName:kLoginFailed object:self];
}

- (NSArray *)getAuthorizedPermissions:(NSArray *)permissions withExtraParams:(NSDictionary *)extraParams{DLog(@"");
    return nil;
}

- (void)tencentDidLogout{DLog(@"");

}

- (BOOL)tencentNeedPerformIncrAuth:(TencentOAuth *)tencentOAuth withPermissions:(NSArray *)permissions{DLog(@"");
    BOOL incrAuthRes = [tencentOAuth incrAuthWithPermissions:permissions];
    return !incrAuthRes;
}

- (BOOL)tencentNeedPerformReAuth:(TencentOAuth *)tencentOAuth{DLog(@"");
    return YES;
}

- (void)tencentDidUpdate:(TencentOAuth *)tencentOAuth{DLog(@"");
}

- (void)tencentFailedUpdate:(UpdateFailType)reason{DLog(@"");
}

- (void)getUserInfoResponse:(APIResponse*) response{DLog(@"");
    [[NSNotificationCenter defaultCenter] postNotificationName:kGetUserInfoResponse object:self  userInfo:[NSDictionary dictionaryWithObjectsAndKeys:response, kResponse, nil]];
}

- (void)getListAlbumResponse:(APIResponse*) response{DLog(@"");
    [[NSNotificationCenter defaultCenter] postNotificationName:kGetListAlbumResponse object:self  userInfo:[NSDictionary dictionaryWithObjectsAndKeys:response, kResponse, nil]];
}

- (void)getListPhotoResponse:(APIResponse*) response{DLog(@"");
    [[NSNotificationCenter defaultCenter] postNotificationName:kGetListPhotoResponse object:self  userInfo:[NSDictionary dictionaryWithObjectsAndKeys:response, kResponse, nil]];
}   

- (void)checkPageFansResponse:(APIResponse*) response{DLog(@"");
    [[NSNotificationCenter defaultCenter] postNotificationName:kCheckPageFansResponse object:self  userInfo:[NSDictionary dictionaryWithObjectsAndKeys:response, kResponse, nil]];
}

- (void)addShareResponse:(APIResponse*) response{DLog(@"");
    [[NSNotificationCenter defaultCenter] postNotificationName:kAddShareResponse object:self  userInfo:[NSDictionary dictionaryWithObjectsAndKeys:response, kResponse, nil]];
}

- (void)addAlbumResponse:(APIResponse*) response{DLog(@"");
    [[NSNotificationCenter defaultCenter] postNotificationName:kAddAlbumResponse object:self  userInfo:[NSDictionary dictionaryWithObjectsAndKeys:response, kResponse, nil]];
}

- (void)uploadPicResponse:(APIResponse*) response{DLog(@"");
    [[NSNotificationCenter defaultCenter] postNotificationName:kUploadPicResponse object:self  userInfo:[NSDictionary dictionaryWithObjectsAndKeys:response, kResponse, nil]];
}

- (void)addOneBlogResponse:(APIResponse*) response{DLog(@"");
    [[NSNotificationCenter defaultCenter] postNotificationName:kAddOneBlogResponse object:self  userInfo:[NSDictionary dictionaryWithObjectsAndKeys:response, kResponse, nil]];
}

- (void)addTopicResponse:(APIResponse*) response{DLog(@"");
    [[NSNotificationCenter defaultCenter] postNotificationName:kAddTopicResponse object:self  userInfo:[NSDictionary dictionaryWithObjectsAndKeys:response, kResponse, nil]];
}

- (void)setUserHeadpicResponse:(APIResponse*) response{DLog(@"");
    [[NSNotificationCenter defaultCenter] postNotificationName:kSetUserHeadPicResponse object:self  userInfo:[NSDictionary dictionaryWithObjectsAndKeys:response, kResponse, nil]];
}

- (void)getVipInfoResponse:(APIResponse*) response{DLog(@"");
    [[NSNotificationCenter defaultCenter] postNotificationName:kGetVipInfoResponse object:self  userInfo:[NSDictionary dictionaryWithObjectsAndKeys:response, kResponse, nil]];
}

- (void)getVipRichInfoResponse:(APIResponse*) response{DLog(@"");
    [[NSNotificationCenter defaultCenter] postNotificationName:kGetVipRichInfoResponse object:self  userInfo:[NSDictionary dictionaryWithObjectsAndKeys:response, kResponse, nil]];
}

- (void)matchNickTipsResponse:(APIResponse*) response{DLog(@"");
    [[NSNotificationCenter defaultCenter] postNotificationName:kMatchNickTipsResponse object:self  userInfo:[NSDictionary dictionaryWithObjectsAndKeys:response, kResponse, nil]];
}

- (void)getIntimateFriendsResponse:(APIResponse*) response{DLog(@"");
    [[NSNotificationCenter defaultCenter] postNotificationName:kGetIntimateFriendsResponse object:self userInfo:[NSDictionary dictionaryWithObjectsAndKeys:response, kResponse, nil]];
}

- (void)responseDidReceived:(APIResponse*)response forMessage:(NSString *)message{
    DLog(@"");
    if (nil == response
        || nil == message)
    {
        return;
    }
    
    NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
                              response, kResponse,
                              message, kMessage, nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:kResponseDidReceived object:self  userInfo:userInfo];
}

- (void)tencentOAuth:(TencentOAuth *)tencentOAuth didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite userData:(id)userData{
    DLog(@"");
}

- (void)tencentOAuth:(TencentOAuth *)tencentOAuth doCloseViewController:(UIViewController *)viewController{
    DLog(@"");
    NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:tencentOAuth, kTencentOAuth,                                                   viewController, kUIViewController, nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:kCloseWnd object:self  userInfo:userInfo];
}

- (BOOL)onTencentResp:(TencentApiResp *)resp{
    DLog(@"");
    return YES;
}

- (BOOL)onTencentReq:(TencentApiReq *)req{
    DLog(@"");
    return YES;
}

- (void)post:(NSDictionary *)userInfo{
DLog(@"");
    [[NSNotificationCenter defaultCenter] postNotificationName:kTencentApiResp object:self userInfo:userInfo];
}

-(BOOL) CheckNetworkState{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    switch ([r currentReachabilityStatus])
    {
        case NotReachable:
            // 没有网络连接
            //NSLog(@"没有网络");
            return FALSE;
            break;
        case ReachableViaWWAN:
            // 使用3G网络
            //NSLog(@"正在使用3G网络");
            break;
        case ReachableViaWiFi:
            // 使用WiFi网络
            //NSLog(@"正在使用wifi网络");
            break;
    }
    return TRUE;
}

@end
